import request from '@/axios';
import { Message } from 'element-ui';

let whiteList = [
  'UR0002', // 超时
  'UR0009' // 其它设备登录
];

let postMgr = function(url, params, callback, method, queryFlag = false) {
  let tempParams = null;
  if (['POST', 'PUT'].includes(method.toUpperCase())) {
    tempParams = {
      url,
      method,
      data: params
    };
    // 一般post请求只需要在请求体里面传参即可，若是需要在路径上也带上，queryFlag设置为true
    if (queryFlag === true) {
      tempParams = Object.assign(tempParams, { params });
    }
  } else if (['GET'].includes(method.toUpperCase())) {
    tempParams = {
      url,
      method,
      params
    };
  }
  return request(tempParams).then(res => {
    let code = res && res.data && res.data.code;
    if (code === 200) {
      callback && callback('succ', res.data, params);
    } else {
      callback && callback('fail', res, params);
      if (!whiteList.includes(code) && res.msg) {
        Message({
          type: 'error',
          message: res.msg + ''
        });
      }
    }
  }).catch(e => {
    callback && callback('fail', e, params);
  });
};

export default postMgr;
